import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { STComponent, STColumn, STRequestOptions, STData } from '@delon/abc/st';
import { SFComponent, SFSchema, SFDateWidgetSchema, SFSelectWidgetSchema, SFSchemaEnum } from '@delon/form';
import { SearchDrawerService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
import { BasicTableComponent } from 'src/app/routes/commom';
import { FreightAccountService } from '../../services/freight-account.service';

@Component({
  selector: 'app-cost-management',
  templateUrl: './cost-management.component.html',
  styleUrls: ['../../../commom/less/commom-table.less']
})
export class CostManagementComponent extends BasicTableComponent implements OnInit {
  @ViewChild('auditModal', { static: false })
  auditModal!: any;
  schema: SFSchema = this.initSF();
  columns: STColumn[] = this.initST();

  selectedRows: any[] = [];

  constructor(
    public service: FreightAccountService,
    private nzModalService: NzModalService,
    private router: Router,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
  }

  ngOnInit(): void {}

  search() {
    this.st?.load(1);
  }

  beforeReq = (requestOptions: STRequestOptions) => {
    if (this.sf) {
      Object.assign(requestOptions.body, {
        ...this.sf?.value,
        feedate: {
          start: this.sf?.value.feedate?.[0] || '',
          end: this.sf?.value.feedate?.[1] || ''
        },
        createTime: {
          start: this.sf?.value.createTime?.[0] || '',
          end: this.sf?.value.createTime?.[1] || ''
        }
      });
    }
    return requestOptions;
  };

  auditAction(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '审核',
      nzContent: this.auditModal,
      nzFooter: [
        {
          label: '拒绝',
          type: 'default',
          onClick: () => {
            modal.destroy();
          }
        },
        {
          label: '通过',
          type: 'primary',
          onClick: () => {
            modal.destroy();
          }
        }
      ]
    });
    modal.afterClose.subscribe(res => {
      this.st.load();
    });
  }


  exportList() {
    this.service.exportStart({ ...this.sf?.value, pageSize: -1 }, this.service.$api_get_reportFeehList);
  }

  routeTo(url: string, params?: any, status?: any) {
    this.router.navigate([url], { queryParams: params });
  }

  private initSF(): SFSchema {
    return {
      properties: {
        feecode: {
          type: 'string',
          title: '费用单号',
          ui: { placeholder: '请输入' }
        },
        billHCode: {
          type: 'string',
          title: '订单号',
          ui: { placeholder: '请输入' }
        },
        waybillHCode: {
          type: 'string',
          title: '运单号',
          ui: {
            placeholder: '请输入'
          }
        },
        feedate: {
          title: '费用日期',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            nzShowTime: true,
          } as SFDateWidgetSchema
        },
        feetype: {
          type: 'string',
          title: '费用类型',
          enum: [
            { label: '全部', value: '' },
            { label: '应收', value: 1 },
            { label: '应付', value: 2 }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
          },
          default: ''
        },
        feeSubId: {
          type: 'string',
          title: '费用科目',
          enum: [
            { label: '全部', value: '全部' },
            { label: '运输费', value: '1475197820443299842' },
            { label: '附加费', value: '1476197820443299842 ' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
          }
        },
        ltdId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getNetworkFreightForwarder(),
          }
        },
        hrto: {
          type: 'string',
          title: '应付对象',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            onSearch: (q: any) => {
              let str = q.replace(/^\s+|\s+$/g, '');
              if (str) {
                return this.service
                  .request(this.service.$api_crm_enterpriceList, { enterpriseName: str })
                  .pipe(map((res: any) => (res as any[]).map(i => ({ label: i.enterpriseName, value: i.enterpriseId } as SFSchemaEnum))))
                  .toPromise();
              } else {
                return of([]);
              }
            },
          } as SFSelectWidgetSchema
        },
        arto: {
          type: 'string',
          title: '应收对象',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            onSearch: (q: any) => {
              let str = q.replace(/^\s+|\s+$/g, '');
              if (str) {
                return this.service
                  .request(this.service.$api_crm_enterpriceList, { enterpriseName: str })
                  .pipe(map((res: any) => (res as any[]).map(i => ({ label: i.enterpriseName, value: i.crmUserId } as SFSchemaEnum))))
                  .toPromise();
              } else {
                return of([]);
              }
            },
          } as SFSelectWidgetSchema
        },
        createTime: {
          title: '创建时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            nzShowTime: true,
          } as SFDateWidgetSchema
        },
        ishrhx: {
          type: 'string',
          title: '应付核销',
          enum: [
            { label: '全部', value: '' },
            { label: '否', value: 0 },
            { label: '是', value: 1 }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
          },
          default: ''
        },
        cno: {
          type: 'string',
          title: '结算客户',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getCloseAccount(),
          }
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return ((this.st.pi -1) * this.st.ps) + idx + 1 + ''
        } 
      },
      { title: '费用单号', fixed: 'left', index: 'feecode', width: 200, className: 'text-left' },
      { title: '网络货运人', index: 'ltdName', width: 220, className: 'text-left' },
      { title: '订单号', index: 'billHCode', width: 200, className: 'text-left' },
      { title: '运单号', index: 'waybillHCode', width: 200, className: 'text-left' },
      { title: '费用日期', index: 'feedate', width: 200, className: 'text-left' },
      { title: '费用类型', index: 'feetypeLabel', width: 150, className: 'text-center' },
      { title: '应付核销', index: 'ishrhx', width: 200, type: 'enum', enum: { 0: '否', 1: '是' }, className: 'text-left' },
      { title: '结算客户', render: 'artocode', width: 200, className: 'text-left' },
      { title: '应收对象', index: 'artoname', width: 200, className: 'text-left' },
      { title: '应付对象', index: 'hrtoname', width: 200, className: 'text-left' },
      { title: '应收/应付金额', render: 'hrmoney', width: 150, className: 'text-right' },
      // { title: '应付金额', render: 'hrmoney', width: 150, className: 'text-right' },
      { title: '收/付款金额', render: 'hrpaymoney', width: 150, className: 'text-right' },
      { title: '开/收票金额', render: 'hrvatmoney', width: 150, className: 'text-right' },
      { title: '创建时间', index: 'createTime', type: 'date', width: 200, className: 'text-center' },
      { title: '状态', index: 'stsLabel', width: 120, className: 'text-center' },
      {
        title: '操作',
        fixed: 'right',
        className: 'text-center',
        width: '110px',
        buttons: [
          {
            text: '浏览',
            click: item => this.routeTo('/financial-management/cost-management/detail/' + item.id, { status: item?.feetypeLabel }),
            acl: { ability: ['FINANCIAL-COST-view'] }
          },
          {
            text: '审核',
            click: item => this.auditAction(item),
            iif: item => item.sts === 2,
            acl: { ability: ['FINANCIAL-COST-audit'] }
          }
          // {
          //   text: '修改',
          //   click: item => this.router.navigate(['/financial-management/cost-management/expenses-receivable/1'], { queryParams: { id: 1 } })
          // }
        ]
      }
    ];
  }
}
